package com.antdant.service;

import com.antdant.entity.Account;
import com.antdant.repository.AccountRepository;
import com.antdant.utils.DataUtils;
import com.antdant.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author liyunc
 * @Date 2021/6/4 22:08
 * @Description:
 * @Version 1.0
 */
@Slf4j
@Service
public class AccountService {

    @Resource
    private AccountRepository accountRepository;

    /**
     * 查询所有财务信息
     *
     * @param current
     * @param size
     * @param account
     * @return
     */
    public Page<Account> getAllAccount(Integer current, Integer size, Account account) {
        Pageable pageable = PageRequest.of(current - 1, size);
        return accountRepository.findAll(new Specification<Account>() {
            @Override
            public Predicate toPredicate(Root<Account> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> list = new ArrayList<>();
                if (DataUtils.isNotEmptyStr(account.getLoginId())) {
                    list.add(criteriaBuilder.like(root.get("loginId"), account.getLoginId()));
                }
                if (account.getType() != -1) {
                    list.add(criteriaBuilder.equal(root.get("type"), account.getType()));
                }
                if (DataUtils.isNotEmptyStr(account.getCreateTime())) {
                    list.add(criteriaBuilder.equal(root.get("createTime"), account.getCreateTime()));
                }
                return criteriaBuilder.and(list.toArray(new Predicate[list.size()]));
            }
        }, pageable);
    }
}
